<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | 询单列表
// +----------------------------------------------------------------------

namespace Admin\Controller;

/**
 *询控制器
 * @author Mike Gao <togaochao@gmail.com>
 */
class InquiryController extends AdminController {

    /**
     * 配置管理
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        /* 查询条件初始化 */
        $map = array();
        if(isset($_GET['status']) && ($_GET['status'] != "" ) )
           $map['status']  =  I('status');
        else
            $map['status'] = array('egt',0);
        if(isset($_GET['charge_man']) )
           $map['charge_man']  =  I('charge_man');
        if($_GET['mano'] != "" ){
            $map['mano']   =   array("like",'%'.trim(I('mano')).'%');
        }
        if($_GET['title'] != "" ){
            $map['title']    =   array('like', '%'.(string)I('title').'%');
        }
        if($_GET['remark'] != "" ){
            $map['remark']    =   array('like', '%'.(string)I('remark').'%');
        }

        if($_GET['note'] != "" ){
            $map['note']    =   array('like', '%'.(string)I('note').'%');
        }
        //time 
        $cond_time = array();
        if( $_REQUEST['start_time'] != '' )
          array_push($cond_time, array( 'egt' , strtotime($_REQUEST['start_time']) ) );
          //$cond_time = array( 'egt' , strtotime($_REQUEST['start_time']) );
        if( $_REQUEST['end_time'] != '' )
          array_push($cond_time, array( 'elt' , strtotime($_REQUEST['end_time']) ) );

        //选择了时间类型,并且时间不为空，则按时间进行搜索
        if( $_REQUEST['time_type'] != "" && 
          ($_REQUEST['end_time'] != '' ||  $_REQUEST['start_time'] != '' ) ){
            switch ($_REQUEST['time_type']) {
              case '1': //修改时间
                $map['update_time '] = $cond_time;
                break;
              case '2': //创建时间
                $map['create_time '] = $cond_time;
                break;
              
              default:  //按下单时间查询
                $map['create_time '] = $cond_time;
                break;
            }
            
        }
        
        $list = $this->lists('Inquiry', $map,'');
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);

        $this->assign('group',C('CONFIG_GROUP_LIST'));
        $this->assign('group_id',I('get.group',0));
        $this->assign('list', $list);
        $this->meta_title = '询单管理';
        $this->display();
    }

    /**
     * 新增询单
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function add(){
        if(IS_POST){
            $Inquiry = D('Inquiry');
            $data = $Inquiry->create();
            if($data){
                if($Inquiry->add()){
                    S('DB_CONFIG_DATA',null);
                    $this->success('新增成功', U('index'));
                } else {
                    $this->error('新增失败');
                }
            } else {
                $this->error($Inquiry->getError());
            }
        } else {
            $this->meta_title = '新增询单';
            $this->assign('info',null);
            $this->display('edit');
        }
    }

    /**
     * 编辑询单
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function edit($id = 0){
        if(IS_POST){
            $Config = D('Inquiry');
            $data = $Config->create();
            if($data){
                if($Config->save()){
                    //记录行为
                    action_log('update_inquiry','quiry',$data['id'],UID);
                    $this->success('更新成功', Cookie('__forward__'));
                } else {
                    $this->error('更新失败');
                }
            } else {
                $this->error($Config->getError());
            }
        } else {
            $info = array();
            /* 获取数据 */
            $info = M('Inquiry')->field(true)->find($id);

            if(false === $info){
                $this->error('获取询单信息错误');
            }
            $this->assign('info', $info);
            $this->meta_title = '编辑询单';
            $this->display();
        }
    }
    
    /**
     * 编辑询单状态 // 做成通用方法 
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function editStatus($id = 0,$tpl="editstatus"){
        if(IS_POST){
            $Config = D('Inquiry');
            $data = $Config->create();
            if($data){
                if($Config->save()){
                    //记录行为
                    action_log('update_inquiry','quiry',$data['id'],UID);
                    $this->success('修改询单成功', Cookie('__forward__'));
                } else {
                    $this->error('修改失败');
                }
            } else {
                $this->error($Config->getError());
            }
        } else {
            $info = array();
            /* 获取数据 */
            $info = M('Inquiry')->field(true)->find($id);

            if(false === $info){
                $this->error('获取询单信息错误');
            }
            $this->assign('info', $info);
            $this->meta_title = '编辑询单';
            $this->display($tpl);
        }
    }

   //check title whether is exist
   public function checkTitle(){
      $title = trim(I('title'));  
      $id_exist = M('Inquiry')->getByTitle($title);
      if($id_exist)
          $data['msg'] = "<font color='red'>已经有标题存在,请确认是否继续操作</font>";
      else
          $data['msg'] = "<font color='green'>没有重复的标题</font>";
      $this->ajaxReturn($data);
   }


   //修改内容
    public function editRemark($id){
       $this->editStatus($id,'editremark');    
    }


   //修改备注
    public function editNote($id){
       $this->editStatus($id,'editnote');    
    }
    /**
     * 批量保存配置//TODO
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function save($config){
        if($config && is_array($config)){
            $Config = M('Config');
            foreach ($config as $name => $value) {
                $map = array('name' => $name);
                $Config->where($map)->setField('value', $value);
            }
        }
        S('DB_CONFIG_DATA',null);
        $this->success('保存成功！');
    }

    // 分配询单
    public function charge() {
        if(!IS_POST){
            $id     =   I('ids');//match id
            $list   =   M("Inquiry")->where("id in (".$id.")")->field('id,mano,title,charge_man')->select();
            if($list) {
                $this->assign('list',$list);
            }
            $this->meta_title = '分配询单';
            $this->display();
        }else{//save charge_man batch
            $Inquiry = M('Inquiry');
            $config = $_POST;
            $count_no = count($config['charge_man']);
            for($i =0; $i < $count_no;$i++) {
                $map = array('id' => $config['id'][$i]);
                $Inquiry->where($map)->setField('charge_man', $config['charge_man'][$i]);
            }
            $this->success('分配成功！');
        }
    }

    //import inquiry data with title and content and product image
    public function import(){
       if(IS_POST){
          $inputFileName = get_csv();
          $inquiry = M('Inquiry');
          if(!is_file($inputFileName))
              $this->error($inputFileName,false,6);
          $row = 0;    
          if (($handle = fopen($inputFileName, "r")) !== FALSE) {
              while (($data = fgetcsv($handle, 0, ',', '"', '"')) !== FALSE) {
                if($row == 0 ){ // start from second line
                     $row ++;
                     continue;
                 }

                $product_link = "<img src='".trim($data['2'])."'>"; //picture link
                $sdata = array(
                  'mano' => D('Inquiry')->genMano(),
                  'title' => trim($data['0']),
                  'remark' => iconv('GBK','utf-8',$product_link."<br/>".$data['1']),
                  'create_time' => time(),
                  'creater' => is_login(), 
                );  
                    
               $inquiry->add($sdata);
               unset($sdata);
             
                $row ++;
              }
          }//end of import
          
          $this->success("成功导入询单 ".($row-1)." 条!" );
 
       }else{
          $this->meta_title = "批量导入询单";
          $this->display();    
       } 
    }

}
